<?php
/**
 * Created by PhpStorm.
 * User: prg
 * Date: 2017/3/9
 * Time: 20:40
 */

//管理员编辑新闻接口
require_once 'db.php';
require_once 'response.php';

header('content-type:text/html;charset:utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');

$id = isset($_POST['newsId']) ? $_POST['newsId'] : '';
$title = isset($_POST['title']) ? $_POST['title'] : '';
$content = isset($_POST['content']) ? $_POST['content'] : '';
//$time = isset($_POST['time']) ? time();

if(!is_numeric($id) || empty($title) || empty($content)) {
    return Response::show(401,'数据不合法');
}

try {
    $connect = Db::getInstance()->connect();
} catch (Exception $e) {
    return Response::show(403,'数据库连接失败');
}

//先用查询语句检查一下传进来的id在news表中是否有对应的数据
//确定有数据了之后，再进行更新，这个时候，有没有更新就是返回值的事情了
//$sql = "SELECT news_maker FROM news WHERE news_id={$id}";
$sql = "SELECT news_maker FROM news WHERE news_id={$id}";

$res = $connect->query($sql);

$data = array(
    'IsSuccess' => false
);

if($res && $res->num_rows>0) {
    $res->free_result();

    $sql = "UPDATE news SET news_title=?,news_content=? WHERE news_id={$id}";
    $mysqli_stmt = $connect->prepare($sql);
    $mysqli_stmt->bind_param('ss',$title,$content);
//    $sql = "UPDATE news SET news_title='测试测试' WHERE news_id=25";
//
//    $res = $connect->query($sql);
//    var_dump($res);
//    var_dump($connect->affected_rows);

    if($mysqli_stmt->execute()) {
        if($mysqli_stmt->affected_rows == 1){
            $data['IsSuccess'] = true;
            return Response::show(200,'新闻编辑成功',$data);
        } else {
            return Response::show(402,'没有进行内容的更新',$data);
        }
    } else {
        return Response::show(404,'新闻编辑操作不成功',$data);
    }

} else {
    return Response::show(400,'没有找到对应的新闻',$data);
}
